package Chatnetwork;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ClientServer {
    private static final int port = 12345;
    //线程安全的无序集合，高并发
    private static Set<PrintWriter> clientWriters = new CopyOnWriteArraySet<>();

    public static void main(String[] args) throws IOException {
        System.out.println("聊天室启动了");
        //创建线程池储存每一个用户的线程
        ExecutorService pool = Executors.newFixedThreadPool(10);
        ServerSocket serverSocket = new ServerSocket(port);
        while (true) {
            //调用线程处理程序
            new ClientHandler(serverSocket.accept(), pool).start();
        }
    }

    //处理线程
    private static class ClientHandler extends Thread {
        private Socket socket;
        private PrintWriter out;
        private BufferedReader in;
        private ExecutorService pool;

        public ClientHandler(Socket socket, ExecutorService pool) {
            this.socket = socket;
            this.pool = pool;
        }

        @Override
        public void run() {
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);
                clientWriters.add(out);
                String message;
                while ((message = in.readLine()) != null) {
                    System.out.println("接收到的message是:" + message);
                    broadcast(message);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            clientWriters.remove(out);
        }

        private void broadcast(String message) {
            for (PrintWriter writer : clientWriters) {
                writer.println(message);
            }
        }
    }

}
